<template>
    <div class="product-detail-page">
      <!-- 面包屑 -->
      <AppBreadcrumb :items="breadcrumbs" />
    
      <div class="container-custom py-8">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <!-- 左侧：产品信息 -->
          <div class="lg:col-span-2">
            <!-- 图片画廊 -->
            <ProductGallery :images="product?.images" class="mb-8" />
          
            <!-- 产品详情 -->
            <div class="card">
              <!-- Tabs -->
              <div class="border-b">
                <nav class="flex space-x-8 px-6">
                  <button
                    v-for="tab in tabs"
                    :key="tab.key"
                    :class="[
                      'py-4 border-b-2 font-medium transition-colors',
                      activeTab === tab.key
                        ? 'border-primary-600 text-primary-600'
                        : 'border-transparent text-gray-600 hover:text-gray-900'
                    ]"
                    @click="activeTab = tab.key"
                  >
                    {{ tab.label }}
                  </button>
                </nav>
              </div>
            
              <!-- Tab 内容 -->
              <div class="p-6">
                <!-- 详细介绍 -->
                <div v-if="activeTab === 'detail'" class="prose max-w-none">
                  <div v-html="product?.detailHtml" />
                </div>
              
                <!-- 演示预览 -->
                <div v-else-if="activeTab === 'demo'">
                  <iframe
                    :src="product?.demoUrl"
                    class="w-full h-[600px] rounded-lg border"
                  />
                </div>
              
                <!-- 用户评价 -->
                <div v-else-if="activeTab === 'reviews'">
                  <ProductReviews :product-id="product?.id" />
                </div>
              </div>
            </div>
          </div>
        
          <!-- 右侧：购买信息 -->
          <div>
            <div class="card sticky top-20">
              <h1 class="text-2xl font-bold mb-4">{{ product?.title }}</h1>
            
              <!-- 评分 -->
              <div class="flex items-center space-x-2 mb-4">
                <div class="flex">
                  <div 
                    v-for="i in 5" 
                    :key="i"
                    :class="i <= (product?.rating || 0) ? 'i-mdi-star text-yellow-500' : 'i-mdi-star-outline text-gray-300'"
                  />
                </div>
                <span class="text-sm text-gray-600">
                  {{ product?.rating }} ({{ product?.reviews }} 评价)
                </span>
              </div>
            
              <!-- 价格 -->
              <div class="mb-6">
                <div class="flex items-baseline space-x-3">
                  <span class="text-3xl font-bold text-primary-600">
                    ¥{{ product?.price }}
                  </span>
                  <span v-if="product?.originalPrice" class="text-lg text-gray-400 line-through">
                    ¥{{ product?.originalPrice }}
                  </span>
                </div>
                <div class="text-sm text-gray-500 mt-1">
                  已售 {{ product?.downloads }} 次
                </div>
              </div>
            
              <!-- 操作按钮 -->
              <div class="space-y-3 mb-6">
                <button class="btn-primary w-full text-lg py-3">
                  立即购买
                </button>
                <button class="btn-outline w-full text-lg py-3">
                  加入购物车
                </button>
              </div>
            
              <!-- 产品信息 -->
              <div class="space-y-3 text-sm border-t pt-4">
                <div class="flex justify-between">
                  <span class="text-gray-600">分类：</span>
                  <span class="font-medium">{{ product?.category }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">难度：</span>
                  <Tag :type="difficultyType">{{ difficultyText }}</Tag>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">更新时间：</span>
                  <span class="font-medium">{{ product?.updatedAt ? formatDate(product.updatedAt) : '' }}</span>
                </div>
              </div>
            
              <!-- 技术栈 -->
              <div class="border-t pt-4 mt-4">
                <div class="text-sm text-gray-600 mb-2">技术栈：</div>
                <div class="flex flex-wrap gap-2">
                  <Tag v-for="tech in product?.tech" :key="tech">
                    {{ tech }}
                  </Tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      
        <!-- 相关推荐 -->
        <section class="mt-12">
          <h2 class="text-2xl font-bold mb-6">相关推荐</h2>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <ProductCard
              v-for="item in relatedProducts"
              :key="item.id"
              :product="item"
            />
          </div>
        </section>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import type { Product } from '~/types'
  import { formatDate } from '~/utils/format'
  
  const route = useRoute()
  const productId = route.params.id as string
  
  // 获取产品详情
  const { data: response } = await useFetch(`/api/products/${productId}`, {
    transform: (res: any) => res?.data
  })
  
  const product = computed(() => response.value as Product)
  
  if (!product.value) {
    throw createError({ statusCode: 404, message: '产品不存在' })
  }
  
  // 获取相关产品
  const { data: relatedResponse } = await useFetch('/api/products/related', {
    params: { id: productId, limit: 4 },
    transform: (res: any) => res?.data?.items || []
  })
  
  const relatedProducts = computed(() => relatedResponse.value as Product[])
  
  const activeTab = ref('detail')
  const tabs = [
    { key: 'detail', label: '详细介绍' },
    { key: 'demo', label: '演示预览' },
    { key: 'reviews', label: '用户评价' },
  ]
  
  const breadcrumbs = computed(() => [
    { label: '源码商城', path: '/products' },
    { label: product.value?.category || '', path: `/products?category=${product.value?.category}` },
    { label: product.value?.title || '', path: '' },
  ])
  
  const difficultyMap: Record<'beginner' | 'intermediate' | 'advanced', { text: string; type: string }> = {
    beginner: { text: '入门', type: 'success' },
    intermediate: { text: '进阶', type: 'primary' },
    advanced: { text: '高级', type: 'warning' },
  }
  
  const difficultyText = computed(() => 
    product.value?.difficulty ? difficultyMap[product.value.difficulty].text : ''
  )
  const difficultyType = computed(() => 
    product.value?.difficulty ? difficultyMap[product.value.difficulty].type : 'primary'
  ) as any
  
  // SEO
  useSeoMeta({
    title: `${product.value?.title || '产品详情'} - 代码小库`,
    description: product.value?.description || '',
    ogTitle: product.value?.title || '',
    ogDescription: product.value?.description || '',
    ogImage: product.value?.cover || '',
  })
  </script>